package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;

@Service
@Slf4j
public class CountDownLatchExampleService {

    public void executeTasksWithLatch() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);

        // 启动三个线程
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    // 模拟任务
                    log.info("线程 {} 开始执行任务", Thread.currentThread().getName());
                    Thread.sleep(1000);
                    log.info("线程 {} 任务完成", Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    log.error("线程 {} 被中断", Thread.currentThread().getName(), e);
                } finally {
                    latch.countDown();
                    log.info("线程 {} 完成后，计数器值：{}", Thread.currentThread().getName(), latch.getCount());
                }
            }).start();
        }

        // 等待所有任务完成
        log.info("等待所有任务完成...");
        latch.await();
        log.info("所有任务已完成");
    }
}
